﻿@inject IHttpService _httpService
@inject IDataCacheService _dataCacheService
@inject NavigationManager NavigationManager
@inject IUserService _userService

<CnGalWebSite.Components.Containers.MiniModeContainer>
    <CnGalWebSite.Components.Containers.MasaTitleContainer Title="留言板" Icon="@IconType.Comment.ToIconString()" Outline>
        @if (CanComment)
        {
            <CommentListView Model="Model" CanDeleted="CanDeleted" OnRefrsh="Refresh" @ref="commentListView"></CommentListView>
            <AuthorizeView>
                <Authorized>
                    <ReplyCommentTip IsChild="false" ObjectId="@ObjectId" Type="Type" OnRefresh="OnOutComment"></ReplyCommentTip>
                </Authorized>
                <NotAuthorized>
                     <MDCard Class="pa-3 mb-4 w-100" Style="align-items: center;">
                        <CnGalWebSite.Components.Buttons.MasaButton Text="登入后发表评论" Rounded OnClick="_userService.Login" Icon="@IconType.Login.ToIconString()" />
                    </MDCard>
                </NotAuthorized>
            </AuthorizeView>
        }
        else
        {
            <CloseCommentTip ></CloseCommentTip>
        }
    </CnGalWebSite.Components.Containers.MasaTitleContainer>
</CnGalWebSite.Components.Containers.MiniModeContainer>

@code {
    [Parameter]
    public bool CanComment { get; set; }
    [Parameter]
    public bool IsShowNotFound { get; set; }
    [Parameter]
    public bool CanDeleted { get; set; }
    [Parameter]
    public string ObjectId { get; set; }
    [Parameter]
    public bool Desc { get; set; }
    [Parameter]
    public CommentType Type { get; set; }
    [Parameter]
    public EventCallback OnChanged { get; set; }

    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }

    public CommentCacheModel Model = new CommentCacheModel();
    CommentListView commentListView;

    protected override async Task OnParametersSetAsync()
    {
        if (CanComment)
        {
            await GetData();
        }
    }

    private async Task Refresh()
    {
        _dataCacheService.CommentDataCatche.Clean((int)Type + "/" + ObjectId);
        await GetData();
    }
    private async Task OnOutComment()
    {
        await Refresh();
        if (commentListView!=null)
        {
            commentListView.PageToEnd();
        }
        await OnChanged.InvokeAsync();
    }
    private async Task GetData()
    {
        try
        {
            Model = await _dataCacheService.CommentDataCatche.GetCache((int)Type + "/" + ObjectId);
            if(Desc)
            {
                //逆序
                Model.Items = Model.Items.OrderByDescending(s => s.CommentTime).ToList();
            }
            StateHasChanged();
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "获取评论列表失败");
        }
    }
}
